from flask import Blueprint, make_response
from query.class_query import find_all_like_class, find_one_class, add_one_class, find_all_class, find_num_of_blogs
from utils.index import request_get, return_format
from utils.utils import return_model

category = Blueprint('class', __name__)


@category.route("/like_all_class", methods=['POST'])
def like_all_class():
    str_part = request_get("str_part")
    find_all_like_data = find_all_like_class(str_part)
    class_datas = []
    for class_item in find_all_like_data["data"]:
        class_datas.append(class_item.class_to_dict())
    if find_all_like_data["msg"] == "success":
        return make_response((return_format("查询成功!", return_model(class_datas, ["class_label", "id"]), 200)))
    elif find_all_like_data["msg"] == "error":
        return make_response((return_format("分类名查询失败!", [], 500)))


@category.route("/add_class", methods=['POST'])
def add_class():
    class_label = request_get("class_label")
    find_one_data = find_one_class({"class_label": class_label})
    if find_one_data["msg"] == "success":
        if find_one_data["data"] is None:
            add_one_data = add_one_class({"class_label": class_label})
            class_datas = add_one_data["data"].class_to_dict()
            if add_one_data["msg"] == "success":
                return make_response((return_format(f"分类名:{class_label},添加成功!", return_model(class_datas, ["class_label", "id"]), 200)))
            elif add_one_data["msg"] == "error":
                return make_response((return_format("添加失败!", None, 500)))
        elif find_one_data["data"] is not None:
            return make_response((return_format("分类名重复,请重新输入!", None, 204)))
    elif find_one_data["msg"] == "error":
        return make_response((return_format("添加失败，请重新提交!", None, 500)))


@category.route("/get_all_class", methods=['POST'])
def get_all_class():
    find_all_data = find_all_class()
    if find_all_data["msg"] == "success":
        data_list = []
        for item in find_all_data["data"]:
            if len(item.class_blog_list) != 0:
                item_data = item.class_to_dict()
                item_data["num"] = len(item.class_blog_list)
                data_list.append(item_data)
        return make_response((return_format("所有分类数据查询成功!", data_list, 200)))
    if find_all_data["msg"] == "error":
        return make_response((return_format("所有分类数据查询失败!", None, 500)))


@category.route("/get_num_of_blogs", methods=['POST'])
def get_num_of_blogs():
    class_id = request_get("class_id")
    find_num = find_num_of_blogs(class_id)
    if find_num["msg"] == "success":
        return make_response((return_format("查询分类相关的博客数量成功!", find_num["data"], 200)))
    if find_num["msg"] == "error":
        return make_response((return_format("查询分类相关的博客数量失败!", None, 500)))
